#pragma once

#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include "Task.hpp"

struct ThreadData
{
    pthread_t tid;
    std::string name;
};

static const int defaultnum=5; //默认线程数量

//实现我们的线程池
template<class T>
class ThreadPool
{
public:
    void Lock()
    {
        pthread_mutex_lock(&_mutex);
    }

    void Unlock()
    {
        pthread_mutex_unlock(&_mutex);
    }

    void Wakeup()
    {
        pthread_cond_signal(&_cond);
    }

    void ThreadSleep()
    {
        pthread_cond_wait(&_cond,&_mutex);
    }

    bool IsQueueEmpty() 
    {
        return _tasks.empty();
    }

    std::string GetThreadName(pthread_t tid)
    {
        for (const auto &ti : _threads)
        {
            if (ti.tid == tid)
                return ti.name;
        }
        return "None";
    }

public:
    //注意我们线程调用的函数要求参数和返回值都是void*
    //但是handler在类中默认有this指针->参数不匹配，可以bind或者声明static或放在类外
    static void *Handler(/*ThreadPool *this,*/void *args)
    {
        ThreadPool<T> *tp=static_cast<ThreadPool<T>*>(args);
        std::string name = tp->GetThreadName(pthread_self());
        while(true)
        {
            tp->Lock();
            
            while(tp->IsQueueEmpty()) //判断任务是否为空
            {
                tp->ThreadSleep(); //条件变量
            }
            T t=tp->Pop(); //取出任务

            tp->Unlock();
            t(); //处理任务 

            std::cout<<name<<" run, "<<"result: "<< t.GetResult()<<std::endl;            
        }
        return nullptr;
    }

    void Start() //启动线程池
    {
        int num=_threads.size();
        for(int i=0;i<num;i++)
        {
            _threads[i].name="thread-"+std::to_string(i+1);
            pthread_create(&(_threads[i].tid),nullptr,Handler,this);
        }
    }

    void Push(const T &t) //向任务队列放入任务
    {
        Lock();
        _tasks.push(t); //放入任务
        Wakeup(); //唤醒线程
        Unlock();
    }

    T Pop() //取出任务
    {
        T t=_tasks.front();
        _tasks.pop();
        return t;
    }

    static ThreadPool<T> *GetInstance() //获取单例对象
    {
        if(nullptr==_tp) //创建单例对象后，不会再有申请和释放锁的操作
        {
            pthread_mutex_lock(&_lock); //保护临界资源
            if(_tp==nullptr)
            {
                std::cout<<"singleton create done"<<std::endl;
                _tp=new ThreadPool<T>();
            }
            pthread_mutex_unlock(&_lock);
        }

        return _tp;
    }

private:
    ThreadPool(const ThreadPool<T>&)=delete;
    const ThreadPool<T>& operator=(const ThreadPool<T>&)=delete;
    
    ThreadPool(int num=defaultnum)
        :_threads(num)
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_cond,nullptr);
    } 

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

private:   
    std::vector<ThreadData> _threads; //线程池
    std::queue<T> _tasks; //任务队列

    pthread_mutex_t _mutex; //锁
    pthread_cond_t _cond; //条件变量

    static ThreadPool<T> *_tp; //获取单例指针
    static pthread_mutex_t _lock; //锁
};

template<class T>
ThreadPool<T> *ThreadPool<T>::_tp=nullptr;

template<class T>
pthread_mutex_t ThreadPool<T>::_lock=PTHREAD_MUTEX_INITIALIZER;